package cn.mrlong.tools.view

import java.awt.*
import javax.swing.JComponent


//TEXTAREA 行号显示插件
class LineNumberHeaderView : JComponent() {
    private val DEFAULT_FONT = Font(Font.MONOSPACED, Font.PLAIN, 11)
    val DEFAULT_BACKGROUD: Color = Color(228, 228, 228)
    val DEFAULT_FOREGROUD: Color = Color.BLACK
    val nHEIGHT: Int = Int.MAX_VALUE - 1000000
    var MARGIN: Int = 5
    var lineHeight: Int = 0
        get() {
            if (field == 0) {
                return fontLineHeight
            }
            return field
        }
        set(lineHeight) {
            if (lineHeight > 0) {
                field = lineHeight
            }
        }
    private var fontLineHeight = 0
    private var currentRowWidth = 0
    private var fontMetrics: FontMetrics? = null

    init {
        font = DEFAULT_FONT
        //foreground = DEFAULT_FOREGROUD
        //background = DEFAULT_BACKGROUD
        setPreferredSize(9999)
    }

    private fun setPreferredSize(row: Int) {
        val width = fontMetrics!!.stringWidth(row.toString())
        if (currentRowWidth < width) {
            currentRowWidth = width
            preferredSize = Dimension(2 * MARGIN + width + 1, nHEIGHT)
        }
    }

    override fun setFont(font: Font) {
        super.setFont(font)
        fontMetrics = getFontMetrics(getFont())
        fontLineHeight = fontMetrics!!.height
    }

    val startOffset: Int
        get() = 4

    override fun paintComponent(g: Graphics) {
        val nlineHeight = lineHeight
        val startOffset = startOffset
        val drawHere = g.clipBounds
        g.color = background
        g.fillRect(drawHere.x, drawHere.y, drawHere.width, drawHere.height)
        g.color = foreground
        val startLineNum = (drawHere.y / nlineHeight) + 1
        val endLineNum = startLineNum + (drawHere.height / nlineHeight)
        var start = (drawHere.y / nlineHeight) * nlineHeight + nlineHeight - startOffset
        for (i in startLineNum..endLineNum) {
            val lineNum = i.toString()
            val width = fontMetrics!!.stringWidth(lineNum)
            g.drawString("$lineNum ", MARGIN + currentRowWidth - width - 1, start)
            start += nlineHeight
        }
        setPreferredSize(endLineNum)
    }

    companion object {
        /**
         * JAVA TextArea行数显示插件
         */
        private const val serialVersionUID = 1L
    }
}
